package com.example.springbootServiceNetwork.demos.web.Controller;

import com.alibaba.fastjson.JSON;
import com.example.springbootServiceNetwork.demos.web.Config.JwtInfo;
import com.example.springbootServiceNetwork.demos.web.Entity.FileInfo;
import com.example.springbootServiceNetwork.demos.web.Service.JwtRedistService;
import com.example.springbootServiceNetwork.demos.web.Service.QRCodeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootServiceNetwork.demos.web.Config.Result;
import com.example.springbootServiceNetwork.demos.web.Service.FileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

import static com.example.springbootServiceNetwork.demos.web.Tool.EncryptUtil.encrypt;
import static com.example.springbootServiceNetwork.demos.web.Tool.WrapperMethodUtil.bollPurvieTool;


@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private FileService fileService;
    @Resource
    private QRCodeService qrCodeService;
    @Value("${file.downloadPath}")
    private String downloadPath;
    @Value("${file.apkPath}")
    private String apkPath;
    @Value("${file.uploadPath}")
    private String uploadPath;

    @Resource
    private JwtRedistService jwtRedistService;

    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    public Result Upload(@RequestParam("file") MultipartFile file) {
        return fileService.fileUpload(file);
    }

    /**
     * 删除文件
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody JSONObject file) {
        return fileService.fileDelete(String.valueOf(file.get("file")));
    }


    /**
     * 文件下载接口
     */
    @GetMapping("/download")
    public ResponseEntity<FileSystemResource> downloadFile(@RequestParam("file") String fileName,@RequestParam("token") String token) {
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename="+fileName);
        try {
           JwtInfo jwtInfo =jwtRedistService.getUserInfo(token);
           if(bollPurvieTool(jwtInfo.getPurview(),"admin" )||
                   bollPurvieTool(jwtInfo.getPurview(),"SVIP" )||
                   bollPurvieTool(jwtInfo.getPurview(),"superAdmin")){
               // 加载文件作为资源
               File file = new File(downloadPath+fileName);
               FileSystemResource resource = new FileSystemResource(file);

               // 返回文件内容
               return ResponseEntity.ok()
                       .headers(headers)
                       .contentLength(file.length())
                       .contentType(MediaType.parseMediaType("application/octet-stream"))
                       .body(resource);
           }else {
               return ResponseEntity.ok()
                       .headers(headers)
                       .contentLength(0)
                       .contentType(MediaType.parseMediaType("application/octet-stream"))
                       .body(null);

           }
       }catch (Exception e){
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(0)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(null);
       }

    }

    /**
     * 下载安装包
     */
    @GetMapping("/downloadApk")
    public ResponseEntity<FileSystemResource> downloadFileApk() {
        // 加载文件作为资源
        File file = new File(apkPath);
        FileSystemResource resource = new FileSystemResource(file);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=UNI__9D0B014.apk");

        // 返回文件内容
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }


    /**
     * 获取QR二维码
     * @param content
     * @return
     * @throws Exception
     */
    @GetMapping("/QR")
    public Result QRcode(@RequestParam("content") String content) throws Exception {
        return qrCodeService.generateQR(content);
    }

    /**
     * 查询文件列表
     */
     @GetMapping("/queryFile")
     public String queryFileInfo(@RequestHeader("token") String token){
         JwtInfo jwtInfo =jwtRedistService.getUserInfo(token);
         if(jwtInfo.getPass()){
             return encrypt(JSON.toJSONString(fileService.queryFileInfo(jwtInfo))) ;
         }else {
             return encrypt(JSON.toJSONString(jwtInfo.getResult())) ;
         }
     }


    /**
     * 文件重命名
     */
    @PostMapping("/rename")
    public Result renameFile(@RequestBody FileInfo fileInfo) throws Exception {
        Result result =new Result();
        // 获取文件路径
        String filePath = uploadPath + fileInfo.getFileName();
        // 创建新文件路径
        String newFilePath = uploadPath +fileInfo.getFileTitle()+"."+ fileInfo.getFileType();
        // 重命名文件
        File oldFile = new File(filePath);
        File newFile = new File(newFilePath);
        boolean pass = oldFile.renameTo(newFile);
        // 返回重命名结果
        if (pass) {
            result.setCode(200);
            result.setMsg("文件重命名成功");
        } else {
            result.setCode(200);
            result.setMsg("文件重命名失败");
        }
        return result;
    }
}